﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context;
using Spring.Context.Support;
using Spring.Objects.Factory;
using System.Collections;

namespace BookStore.Platform.spring
{
    public static class SpringContext
    {
        private static IApplicationContext current;
        private static object sync = new object();

        public static IApplicationContext Current 
        {
            get
            {
                lock (sync)
                {
                    if (current == null)
                    {
                        return ContextRegistry.GetContext();
                    }
                    else
                        return current;
                }
            }
        }
        

        public static T GetObject<T>(this IListableObjectFactory applicationContext) where T : class
        {
            IDictionary containedObjects = applicationContext.GetObjectsOfType(typeof(T));
            if (containedObjects.Count == 0) return null;

            if (containedObjects.Count == 1)
                return containedObjects[containedObjects.Keys.Cast<object>().First()] as T;

            string objectId = string.Empty;
            Type type = typeof(T);
            if (type.IsInterface && type.Name.StartsWith("I", StringComparison.Ordinal) && type.Name.Length > 1)
                objectId = type.Name.Substring(1);
            else
                objectId = type.Name;

            if (containedObjects.Contains(objectId))
                return containedObjects[objectId] as T;

            return null;
        }

      
        public static T GetObject<T>(this IObjectFactory applicationContext, string objectId) where T : class
        {
            if (!applicationContext.ContainsObject(objectId)) return null;
            return applicationContext.GetObject(objectId) as T;
        }
    }
}
